/** 
 * @file V3F Node.js HTTP Server file.
 * @author wuwenjun555 <wuwenjun555@gmail.com>
 * @copyright wuwenjun555 2023
 * @license MIT
 * @version 0.0.1
 */

const
  is0Arr = function (o) { return o == !1; },
  rootPath = process.cwd(), dbPath = rootPath + '\\db\\V3F.db', nFs = require('fs'),
  getDBData = function () { return JSON.parse(nFs.readFileSync(dbPath, 'utf-8')) },
  setDBData = s => {
    const ret = { r: 0 };
    try {
      nFs.writeFileSync(dbPath, s);
    } catch (e) {
      ret.r = e;
    } finally {
      return ret;
    }
  },
  getTasks = function () {
    const v3fDB = getDBData();
    return v3fDB;
  },
  saveTasks = function (p) {
    const v3fDB = getDBData(), tIdx = v3fDB.tasksIndex || [], len = v3fDB.tasks.length;
    if (is0Arr(tIdx)) {
      for (let i = 0; i < len; i++) {
        tIdx.push(v3fDB.tasks[i].taskID);
      }
      v3fDB.tasksIndex = tIdx;
    }
    const i = tIdx.indexOf(p.taskID);
    if (i < 0) {
      v3fDB.tasks.push(p);
      tIdx.push(p.taskID);
    } else {
      v3fDB.tasks[i] = p;
    }
    return setDBData(JSON.stringify(v3fDB));
  },
  delTasks = function (p) {
    const v3fDB = getDBData(), ts = v3fDB.tasks, tIdx = v3fDB.tasksIndex, ids = p.taskIDs, len = ids.length;
    if (len > 1) {
      v3fDB.tasks = ts.filter(t => { return !ids.includes(t.taskID); });
      v3fDB.tasksIndex = tIdx.filter(id => { return !ids.includes(id); });
    } else {  //case len == 1;
      const i = tIdx.indexOf(ids[0]);
      ts.splice(i, 1);
      tIdx.splice(i, 1);
    }
    //case len == 0 is not exist; 
    return setDBData(JSON.stringify(v3fDB));
  },
  // util
  hasDir = function (url) {
    url = url || 'rootPath';
    console.log(url);
    return nFs.existsSync() ? 1 : 0;
  };

module.exports = {
  getTasks: getTasks,
  saveTasks: saveTasks,
  delTasks: delTasks,
  hasDir: hasDir
};
